<template>

  <div class="tags" v-if="tags.length > 0">
    <div>点击插入：</div>
    <div class="tags-group">
      <span v-for="item in tags" @click="insertTag" class="exadmin-tag">{{ item }}</span>
    </div>
  </div>
  <editor
        v-model="value"
        :init="init"
        :id="elementId"
        :tag-name="tag"

  />
</template>
<script>

import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'
// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/

import 'tinymce/plugins/advlist'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/code'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/link'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/media'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/noneditable'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/save'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/spellchecker'
import 'tinymce/plugins/tabfocus'
import 'tinymce/plugins/table'
import 'tinymce/plugins/template'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/textpattern'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/print'
import 'tinymce/icons/default'
import {defineComponent, reactive, watch,watchEffect ,onMounted, toRefs,nextTick, onBeforeUnmount,onUpdated,onBeforeUpdate} from "vue";
import {uniqidMd5} from '@/utils'
import useUploader from '@/hook/uploader'
import {useVModel} from "@vueuse/core";
export default defineComponent({
  name: 'ExTinymceEditor',
  components: {
    Editor
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: [String, Number],
      default: 500
    },
    width: {
      type: [String, Number],
      default: 'auto'
    },
    toolbar: {
      type: [String, Array],
      default: 'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image axupimgs media code | removeformat fullscreen'
    },
    options: {
      type: [Object, Array],
      default: {}
    },
    tags: {
      type: Array,
      default: []
    },
    upload: {
      type: [Object, Array],
      default: {}
    },
  },
  emits: ['update:value'],
  setup(props, ctx) {
    const BASE_URL = import.meta.env.BASE_URL
    let upload = useUploader(props.upload)
    const value  = useVModel(props,'value',ctx.emit)
    onBeforeUnmount(()=>{
      upload.uploader.cancel()
      upload = null
    })
    const state = reactive({
      init: {
        base_url: BASE_URL+'tinymce',
        language_url: BASE_URL+`tinymce/langs/zh_CN.js`,
        language: 'zh_CN',
        skin_url: BASE_URL+`tinymce/skins/ui/oxide`,
        content_css: BASE_URL+`tinymce/skins/content/default/content.css`,
        height: props.height,
        width: props.width,
        fontsize_formats:'10px 11px 12px 14px 16px 18px 20px 24px 36px',
        menubar: false,
        plugins: 'axupimgs advlist anchor autolink autosave code codesample directionality fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak preview print save searchreplace spellchecker tabfocus table template textpattern visualblocks visualchars wordcount',
        toolbar: props.toolbar,
        file_picker_types: 'media',
        video_template_callback: (data) => {
          return '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls" src="' + data.source + '"></video>';
        },
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype == 'media') {
            let input = document.createElement('input');//创建一个隐藏的input
            input.setAttribute('type', 'file');
            input.onchange = function (e) {
              let file = this.files[0];//选取第一个文件
              editorUpload(file,callback)
            }
            //触发点击
            input.click();
          }
        },
        branding: false,
        convert_urls: false,
        content_style: 'img {max-width:100% !important } .ex-admin-tag{color:#1890ff;background:#e6f7ff;box-sizing:border-box;margin:0 8px 0 0;font-variant:tabular-nums;list-style:none;font-feature-settings:"tnum";display:inline-block;height:auto;padding:0 7px;font-size:12px;line-height:20px;white-space:nowrap;border:1px solid #91d5ff;border-radius:2px;opacity:1;transition:all .3s}',
        external_plugins: {
          'powerpaste': BASE_URL+'tinymce/plugins/powerpaste/plugin.min.js'
        },
        images_upload_handler: (blobInfo, succFun, failFun) => {
          let file = blobInfo.blob()
          file = new File([file], file.name)
          editorUpload(file,succFun)

        }
      },
      elementId: uniqidMd5(),
      tag: uniqidMd5(),
    })
    state.elementId = uniqidMd5()
    Object.assign(state.init, props.options)
    watch(()=>[props.height,props.width,props.toolbar,props.options],()=>{
      if(tinymce.get(state.elementId)){
        tinymce.get(state.elementId).remove()
        Object.assign(state.init,{width:props.width,height:props.height,toolbar:props.toolbar,selector:'#'+state.elementId}, props.options)
        nextTick(()=>{
          tinymce.init(state.init)
        })
      }
    })
    function editorUpload(file,succFun){
      upload.uploader.addFile(file)
      upload.watch({
        success:url=>{
          succFun(url)
        }
      })
    }
    function insertTag(e) {
      const ed = tinymce.get(state.elementId);                // get editor instance
      ed.execCommand('mceInsertContent', false, '<span class="ex-admin-tag" contenteditable="false">' + e.target.innerText + '</span>')
      value.value = ed.getContent()
    }
    return {
      value,
      insertTag,
      ...toRefs(state),
    }
  }
})
</script>
<style lang="scss" scoped>

.tags {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

</style>

